﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Zhuang.WinForm.ControlLibrary.Components.Grid
{
    public class MyDataGridView: DataGridView
    {
        //protected override bool ProcessDialogKey(Keys keyData)
        //{
        //    if (keyData == Keys.Enter)
        //    {
        //        this.CommitEdit(DataGridViewDataErrorContexts.Commit);
        //        this.EndEdit();

        //        return true;
        //    }
        //    else {
        //        return base.ProcessDialogKey(keyData);
        //    }
            
        //}

        //定义事件参数类
        public class MyEventArgs : EventArgs
        {
            public readonly char KeyToRaiseEvent;
            public MyEventArgs(char keyToRaiseEvent)
            {
                KeyToRaiseEvent = keyToRaiseEvent;
            }
        }

        //定义delegate
        public delegate void MyEventHandler(object sender, MyEventArgs e);


                //用event 关键字声明事件对象
        public event MyEventHandler MyEvent;

        //事件触发方法
        protected virtual void OnMyEvent(MyEventArgs e)
        {
            if (MyEvent != null)
                MyEvent(this, e);
        }

        //引发事件
        public void RaiseEvent(char keyToRaiseEvent)
        {
            MyEventArgs e = new MyEventArgs(keyToRaiseEvent);
            OnMyEvent(e);
        }


        //监听事件的类
        public class MyEventListener
        {
            //定义处理事件的方法，他与声明事件的delegate具有相同的参数和返回值类型
            public void KeyPressed(object sender, MyDataGridView.MyEventArgs e)
            {
                Console.WriteLine("发送者：{0}，所按得健为：{1}", sender, e.KeyToRaiseEvent);
            }

            //订阅事件
            public void Subscribe(MyDataGridView evenSource)
            {
                evenSource.MyEvent += new MyDataGridView.MyEventHandler(KeyPressed);
            }
            //取消订阅事件
            public void UnSubscribe(MyDataGridView evenSource)
            {
                evenSource.MyEvent -= new MyDataGridView.MyEventHandler(KeyPressed);
            }
        }



        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.OnMyEvent(new MyEventArgs('a'));
                //base.OnKeyDown(e); 
            }
            else
            {
                base.OnKeyDown(e); 
            }
        }

        protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e)
        {
            base.OnCellMouseDown(e);
            //base.OnMouseClick(e);

            //if(e.RowIndex>0&&e.ColumnIndex>0)
            //this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
        }

       
    }
}
